package cn.neusoft.service.impl;

import cn.neusoft.bean.Order;
import cn.neusoft.dao.impl.OrderDao;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.OrderQuery;
import cn.neusoft.service.IOrderService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;

import java.util.List;

public class OrderService implements IOrderService {
    private OrderDao ordersDao;
    public OrderService() {
        ordersDao = new OrderDao();
    }
    @Override
    public ResultBean add(Order order) throws Exception {
        if (order ==null|| order.getUserId()==null) {
            return ResultBean.ERROR("params null");
        }
        int i=ordersDao.add(order);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add orders fail");
    }

    @Override
    public ResultBean update(Order order) throws Exception {
        if (order ==null|| order.getUserId()==null) {
            return ResultBean.ERROR("params null");
        }
        int i=ordersDao.update(order);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update orders fail");
    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
        if (id==null) {
            return ResultBean.ERROR("params null");
        }
        int i=ordersDao.delete(id);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete orders fail");
    }

    @Override
    public ResultBean getById(Integer id) throws Exception {
        if (id==null) {
            return ResultBean.ERROR("params null");
        }
        Order order =ordersDao.getById(id);
        return order ==null?ResultBean.ERROR("get cart by id fail"):ResultBean.SUCCESS(order);
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<Order> orders = ordersDao.getAll();
        return ResultBean.SUCCESS(orders);
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {

        if (baseQuery==null) {
            baseQuery=new OrderQuery();
        }

        PageBean<Order> pageBean = new PageBean<>();

        int count = ordersDao.getCount(baseQuery);
        pageBean.setTotalRows(count);

        if (count%baseQuery.getPageCount()==0) {
            pageBean.setTotalRows(count/baseQuery.getPageCount());
        }else {
            pageBean.setTotalRows(count/baseQuery.getPageCount()+1);
        }

        List<Order> orderList = ordersDao.getByPage(baseQuery);
        pageBean.setData(orderList);

        return ResultBean.SUCCESS(pageBean);

    }

    @Override
    public ResultBean bathDel(List<Integer> ids) throws Exception {
        if (ids == null || ids.size()==0){
            return ResultBean.ERROR("params null");
        }

        for (Integer id:ids){
            ordersDao.delete(id);
        }
        return ResultBean.SUCCESS();

    }

}

